<?php

declare(strict_types=1);

namespace WebTus;

/**
 * 存储
 * Class TusStoreAbstract
 */
abstract class TusStoreAbstract
{
    public const FILE_SKIP = 0;
    public const FILE_COVER = 1;
    public const FILE_DUPLICATE = 2;

    /**
     * @var TusService $tus
     */
    public $tus;
    public $uploadExpires = 86400; //上传文件过期时间 0不做处理 单位秒
    public $chunkSize = 65536; //块数据读取大小 64k go的默认buf是32k
    public $fileCoverWays = self::FILE_DUPLICATE; //重复文件名处理方式 0跳过 1覆盖 2重复
    /**
     * @var string 文件去重算法 空0false将不计算hash去重 如md5,sha1,sha256,sha512
     */
    public $fileHashAlgorithm = '';

    public static $cli = PHP_SAPI == 'cli';
    protected $hash_init = []; //hash计算对象数组 cli模式下使用
    protected $dir;
    protected $tempDir;

    protected function file2path(string $path, string $name, bool $dir = true): string
    {
        return ($dir ? $this->dir : '') . $path . ($path !== '' ? '/' : '') . $name;
    }

    //路径处理
    public function fmtPath(string $path): string
    {
        //自定义路径处理
        if ($path !== '') {
            $path = trim(trim($path), '/');
            if ($path !== '') {
                $items = explode('/', $path);
                foreach ($items as $item) {
                    if (!TusService::isValidName($item)) {
                        throw new \Exception('Invalid path');
                    }
                }
            }
        } else {
            $path = date("Ymd/Hi");
        }
        return $path;
    }
}
